<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="sockjs.min.js"></script>
    <script src="stomp.js"></script>
    <script src="jquery-3.1.1.js"></script>
</head>
<body>
   <button id="conId" onclick="go()">连接</button>
   <button id="closeId" disabled onclick="closeCon()">关闭</button>
   <input type="text" name="content" id="content">
   <button id="sendId"  disabled onclick="sendMessage()">发送给李四</button>
   <span id="msg"></span>
   <hr>
   收到消息:
   <div id="conentId">

   </div>
</body>
</html>

<script>
    var stomp = null;
    var isInitiative = false; //是否主动断开
    function go()
    {
        var token = "zhangshang";
        var sock = new SockJS("/ws");
        stomp = Stomp.over(sock);
        isInitiative = false;
        stomp.connect({Authorization:token},function (e) {
            console.log("连接成功");
            $("#msg").html('连接成功');
            $("#closeId").attr("disabled",false);
            $("#sendId").attr("disabled",false);

            $("#conId").attr("disabled",true);
            stomp.subscribe("/topic/subscribeTest/1",handleNotification);

            stomp.subscribe("/user/queue/test",handleP2PNotification);
        }, function (err){
            console.log("连接失败");
            $("#msg").html('连接失败');
            $("#sendId").attr("disabled",true);
            if (isInitiative==false)
            {
                go();
            }
        });

    }

    function  closeCon() {
         isInitiative  = true;
        $("#msg").html('已断开');
        $("#closeId").attr("disabled",true);
        $("#conId").attr("disabled",false);
        $("#sendId").attr("disabled",true);
         stomp.disconnect();
    }


    function handleNotification(message) {
        //一般获取群聊用户列表
        console.log("群发收到的消息")
        console.log(message);

        $("#conentId").html(message.body);

    }

    function handleP2PNotification(message) {
        console.log("单发发收到的消息")
        console.log(message);
        if (message.body=="强制下线")
        {
            alert("在别处登录，被强制下线");
        }
        else{
            $("#conentId").html(message.body);
        }
    }

    function sendMessage() {
        //stomp.send('/user/queue/MessageTest',{}, JSON.stringify({message:$("#content").val(),to:'lishi_'}));
        stomp.send('/topic/subscribeTest/1',{}, JSON.stringify({message:$("#content").val()}));
    }
</script>